package com.lulu.landslidedemo04;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;


/**
 * Created by lulu on 2017/3/18.
 * <br/><br/>
 * <b>横向滑动控件 for e_ink</b><br/><br/>
 *
 * 属性：<br/>
 * <p>maxItemCount：每页显示的最大个数</p>
 * <p>isNeedNavigation：是否需要底部的导航  【1/6】</p>
 * <p>slideMode：滑动模式 （上下滑动，左右）</p>
 */

public class LandSlideView<T> extends FrameLayout implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, BaseLandSlideAdapter.OnRefreshPage {
    private static final String TAG = "lulu";
    private Context mContext;
    private ListView mNoScrollListView;
    private boolean mIsNeedNavigation;
    private GestureDetectorCompat mGestureDetector;//手势控制
    public static final float FLIP_DISTANCE = 100;//滑动距离
    private BaseLandSlideAdapter<T> mAdapter;
    private TextView mPageNavigation;
    private NoScrollListViewAdapter<T> mNoScrollListViewAdapter;
    private int mItemCount;

    private int mSlideMode;//滚动模式
    public static final int SLIDE_MODE_LEFT_TO_RIGHT = 100;
    public static final int SLIDE_MODE_UP_TO_DOWN = 101;
    public static final int SLIDE_MODE_DEFAULT = SLIDE_MODE_LEFT_TO_RIGHT;

    private View mFooterView;//滑动控件footerView

    public LandSlideView(@NonNull Context context, boolean isNeedNavigation, int itemCount, int slideMode) {
        super(context);
        mIsNeedNavigation = isNeedNavigation;
        mItemCount = itemCount;
        mSlideMode = slideMode;
        initView(context);
    }

    public LandSlideView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LandSlideView);
        mIsNeedNavigation = typedArray.getBoolean(R.styleable.LandSlideView_isNeedNavigation, true);
        mItemCount = typedArray.getInt(R.styleable.LandSlideView_maxItemCount, 5);
        mSlideMode = typedArray.getInt(R.styleable.LandSlideView_slideMode, SLIDE_MODE_DEFAULT);
        initView(context);
    }

    private void initView(Context context) {
        setClickable(true);//必须添加
        mContext = context;
        mGestureDetector = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener() {
            /**
             * e1 The first down motion event that started the fling. e2 The
             * move motion event that triggered the current onFling.
             *
             * @param e1
             * @param e2
             * @param velocityX
             * @param velocityY
             * @return true表示消费了 false表示未消费
             */
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                switch (mSlideMode) {
                    case SLIDE_MODE_LEFT_TO_RIGHT:
                        float e1X = e1.getX();
                        float e2X = e2.getX();
                        if (e1X - e2X > FLIP_DISTANCE) {
                            onNextPager();
                            return true;
                        }
                        if (e2X - e1X > FLIP_DISTANCE) {
                            onPrePager();
                            return true;
                        }
                        break;
                    case SLIDE_MODE_UP_TO_DOWN:
                        float e1Y = e1.getY();
                        float e2Y = e2.getY();
                        if (e1Y - e2Y > FLIP_DISTANCE) {
                            onNextPager();
                            return true;
                        }
                        if (e2Y - e1Y > FLIP_DISTANCE) {
                            onPrePager();
                            return true;
                        }

                        break;
                }
                return false;
            }
        });
        View view = LayoutInflater.from(context).inflate(R.layout.land_slide_view, this, false);
        mNoScrollListView = (ListView) view.findViewById(R.id.no_scroll_list);
        mNoScrollListView.setOnItemClickListener(this);
        mNoScrollListView.setOnItemLongClickListener(this);
        mPageNavigation = ((TextView) view.findViewById(R.id.pager_navigation));
        if (mIsNeedNavigation) {
            mPageNavigation.setVisibility(VISIBLE);
        } else {
            mPageNavigation.setVisibility(GONE);
        }
        addView(view);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!mGestureDetector.onTouchEvent(ev)) {
            return super.dispatchTouchEvent(ev);
        }
        return true;
    }
    
    public void onNextPager() {
        int mode;
        List<T> currentPageList = null;
        int curPageIndex = mAdapter.getCurPageIndex();
        int pageCount = mAdapter.getPageCount();
        if (curPageIndex < pageCount) {
            curPageIndex++;
            mAdapter.setCurPageIndex(curPageIndex);
            currentPageList = mAdapter.notifyDataSetChanged();
            mode = OnLandViewPageChangeListener.PAGER_CHANGE_MODE_NEXT_NO_END;
        } else {
            mode = OnLandViewPageChangeListener.PAGER_CHANGE_MODE_NEXT_END;
        }
        if (mPageChangeListener != null) {
            mPageChangeListener.onChangePage(curPageIndex, pageCount, mode, currentPageList);
        }
    }

    public void onPrePager() {
        int mode;
        List<T> currentPageList = null;
        int curPageIndex = mAdapter.getCurPageIndex();
        int pagerCount = mAdapter.getPageCount();
        if (curPageIndex > 1) {
            curPageIndex--;
            mAdapter.setCurPageIndex(curPageIndex);
            currentPageList = mAdapter.notifyDataSetChanged();
            mode = OnLandViewPageChangeListener.PAGER_CHANGE_MODE_PRE_NO_END;
        } else {
            mode = OnLandViewPageChangeListener.PAGER_CHANGE_MODE_PRE_END;
        }
        if (mPageChangeListener != null) {
            mPageChangeListener.onChangePage(curPageIndex, pagerCount, mode, currentPageList);
        }
    }

    @Override
    public void refreshPageNavigation(String text) {
        mPageNavigation.setText(text);
    }

    @Override
    public void refreshPageFooter(int index, int count) {
        checkAddFooter(index, count);
    }

    //用来检查是否添加Footer
    private void checkAddFooter(int index, int count) {
        if (index == count && mAdapter.isHaveFooter()) {
            mNoScrollListView.removeFooterView(mFooterView);
            mNoScrollListView.addFooterView(mFooterView);
        } else {
            mNoScrollListView.removeFooterView(mFooterView);
        }
    }

    /**
     * 翻页变化监听 接口
     */
    public interface OnLandViewPageChangeListener<L> {

        int PAGER_CHANGE_MODE_NEXT_NO_END = 0x1;
        int PAGER_CHANGE_MODE_PRE_NO_END = 0x2;
        int PAGER_CHANGE_MODE_NEXT_END = 0x3;
        int PAGER_CHANGE_MODE_PRE_END = 0x4;

        /**
         * <p>变化 模式</p>
         * <p>PAGER_CHANGE_MODE_NEXT_NO_END : 翻下一页 非页尾</p>
         * <p>PAGER_CHANGE_MODE_PRE_NO_END：翻上一页 非页头</p>
         * <p>PAGER_CHANGE_MODE_NEXT_END：翻下一页 页尾</p>
         * <p>PAGER_CHANGE_MODE_PRE_END：翻上一页 页头</p>
         * @param currentPagerIndex 当前页
         * @param pageCount 总页数
         * @param changeMode 变化模式
         * @param currentPagerList 当前页的数据
         */
        void onChangePage(int currentPagerIndex, int pageCount, int changeMode, List<L> currentPagerList);
    }

    private OnLandViewPageChangeListener mPageChangeListener;

    /**
     * 控件Item点击回调接口
     */
    public interface OnItemClickListener {
        void onItemClick(AdapterView<?> parent, View view, int position, long id);
    }

    private LandSlideView.OnItemClickListener mItemClickListener;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //int newPosition = mAdapter.getRealPosition(position);
        if (mItemClickListener != null) {
            mItemClickListener.onItemClick(parent, view, position, id);
        }
    }

    /**
     * 长按事件
     */
    public interface OnItemLongClickListener {
        boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id);
    }

    private LandSlideView.OnItemLongClickListener mItemLongClickListener;

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        boolean ret = false;
        //int newPosition = mAdapter.getRealPosition(position);
        if (mItemLongClickListener != null) {
            ret = mItemLongClickListener.onItemLongClick(parent, view, position, id);
        }
        return ret;
    }

   ///////////////////////////////////////////////////////////////////////////
    // 对外开放的方法
    ///////////////////////////////////////////////////////////////////////////
    public void setAdapter(BaseLandSlideAdapter<T> adapter) {
        mAdapter = adapter;
        mNoScrollListViewAdapter = new NoScrollListViewAdapter<T>(mContext, mAdapter);
        mNoScrollListView.setAdapter(mNoScrollListViewAdapter);
        mAdapter.setListViewAdapter(mNoScrollListViewAdapter);//用于ListView的数据更新
        mAdapter.setRefreshPage(this);//用于底部导航的更新
        mAdapter.setItemCount(mItemCount);
    }

    public void addFooterView(View view) {
        mAdapter.setHaveFooter(true);
        if (mFooterView != null) {
            mNoScrollListView.removeFooterView(mFooterView);
        }
        mFooterView = view;
    }
    public void removeFooterView() {
        mAdapter.setHaveFooter(false);
    }

    public void setPageChangeListener(OnLandViewPageChangeListener pageChangeListener) {
        mPageChangeListener = pageChangeListener;
    }

    public void setOnItemClickListener(LandSlideView.OnItemClickListener itemClickListener) {
        mItemClickListener = itemClickListener;
    }

    public void setOnItemLongClickListener(LandSlideView.OnItemLongClickListener itemLongClickListener) {
        mItemLongClickListener = itemLongClickListener;
    }

}
